
package com.hlkj.pay.service.order.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelComplaintOrderContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRiskOrderContext;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.dto.order.ComplaintOrderChannelQueryDto;
import com.hlkj.pay.gateway.order.IChannelComplaintGateway;
import com.hlkj.pay.gateway.order.IChannelRiskGateway;
import com.hlkj.pay.infrastructure.mapper.order.OrderComplaintChannelMapper;
import com.hlkj.pay.infrastructure.model.order.OrderComplaintChannelDO;
import com.hlkj.pay.service.CommonSnFilterService;
import com.hlkj.pay.service.order.IOrderComplaintChannelService;
import com.hlkj.pay.vo.order.req.ComplaintDeleteReq;
import com.hlkj.pay.vo.order.resp.OrderComplaintChannelResp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;

/**
 * @author HlpayTeam
 * @date 2024/11/07 10:46
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderComplaintChannelServiceImpl extends CommonSnFilterService implements IOrderComplaintChannelService {

    private final OrderComplaintChannelMapper orderComplaintChannelMapper;

    private final IChannelComplaintGateway channelComplaintGateway;

    private final IChannelRiskGateway channelRiskGateway;

    @Value("${hlkj.domain}")
    private String domain;

    @Override
    public CommonResult<Void> addComplaintChannel(OrderComplaintChannelDO orderComplaintChannelDO) {
        orderComplaintChannelMapper.insert(orderComplaintChannelDO);
        return CommonResult.success();
    }

    @Override
    public PageResult<OrderComplaintChannelDO> queryPage(ComplaintOrderChannelQueryDto complaintOrderChannelQueryDto) {
        complaintOrderChannelQueryDto.setSortingFields("id");
        return orderComplaintChannelMapper.selectPage(complaintOrderChannelQueryDto,buildWrapper(complaintOrderChannelQueryDto));
    }


    @Override
    public OrderComplaintChannelDO queryDetail(Long id) {
        return orderComplaintChannelMapper.selectById(id);
    }

    public CommonResult<OrderComplaintChannelResp> queryChannelDetail(Long id) {
        OrderComplaintChannelDO orderComplaintChannelDO = orderComplaintChannelMapper.selectById(id);
        if(orderComplaintChannelDO == null){
            return CommonResult.error(CommonResultCode.DATA_NOT_EXIST);
        }
        OrderComplaintChannelResp orderComplaintChannelResp =  BeanUtil.copy(orderComplaintChannelDO,OrderComplaintChannelResp.class);
        if(orderComplaintChannelDO.getType() == 2){
            return CommonResult.success(orderComplaintChannelResp);
        }

        // 查询投诉回调地址
        ChannelComplaintOrderContext channelComplaintOrderContext = new ChannelComplaintOrderContext();
        channelComplaintOrderContext.setOrderComplaintChannelDO(orderComplaintChannelDO);
        channelComplaintOrderContext.setProcessStatus(true);
        CommonResult<String> commonResult = channelComplaintGateway.query(channelComplaintOrderContext);
        if(channelComplaintOrderContext.isProcessStatus() && StrUtil.isNotEmpty(commonResult.getData())){
            orderComplaintChannelResp.setComplaintNotifyUrl(commonResult.getData());
            // 更新数据库
            OrderComplaintChannelDO update = new OrderComplaintChannelDO();
            update.setId(id);
            update.setNotifyFlag(1);
            update.setComplaintNotifyUrl(commonResult.getData());
            orderComplaintChannelMapper.updateById(update);
        }

        // 查询风险回调地址
        ChannelRiskOrderContext channelRiskOrderContext = new ChannelRiskOrderContext();
        channelRiskOrderContext.setOrderComplaintChannelDO(orderComplaintChannelDO);
        channelRiskOrderContext.setProcessStatus(true);
        commonResult = channelRiskGateway.query(channelRiskOrderContext);
        if(channelRiskOrderContext.isProcessStatus() && StrUtil.isNotEmpty(commonResult.getData())){
            orderComplaintChannelResp.setRiskNotifyUrl(commonResult.getData());
            // 更新数据库
            OrderComplaintChannelDO update = new OrderComplaintChannelDO();
            update.setId(id);
            update.setRiskFlag(1);
            update.setRiskNotifyUrl(commonResult.getData());
            orderComplaintChannelMapper.updateById(update);
        }


        orderComplaintChannelResp.setDefaultComplaintNotifyUrl(domain+MerchantExtConstant.MERCHANT_ORDER_COMPLAINT_CALLBACK_URL+id);
        orderComplaintChannelResp.setDefaultRiskNotifyUrl(domain+MerchantExtConstant.MERCHANT_ORDER_RISK_CALLBACK_URL+id);
        return CommonResult.success(orderComplaintChannelResp);
    }

    @Override
    public CommonResult<Void> updateOrderComplaintChannel(OrderComplaintChannelDO channelDO) {

        try {
            if (channelDO.getId() == null) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            OrderComplaintChannelDO orderComplaintChannelDO = queryDetail(channelDO.getId());
            if (orderComplaintChannelDO == null) {
                return CommonResult.error(CommonResultCode.DATA_NOT_EXIST);
            }
            // 判断是否更新投诉回调地址
            if(StrUtil.isNotEmpty(channelDO.getComplaintNotifyUrl())){
                // 合法校验
                if(!channelDO.getComplaintNotifyUrl().startsWith("https")){
                    return CommonResult.error(CommonResultCode.PARAMETER_ERROR);
                }

                orderComplaintChannelDO = queryDetail(channelDO.getId());
                // 检查是否已经配置渠道
                if(StrUtil.isEmpty(orderComplaintChannelDO.getBaseConfig()) || StrUtil.isEmpty(orderComplaintChannelDO.getChannelCode())){
                    return CommonResult.error(MerchantResultCode.MERCHANT_COMPLAINT_CONFIG_NOT_EXIST);
                }
                // 校验是否更新过
                channelDO.setNotifyFlag(orderComplaintChannelDO.getNotifyFlag());

                ChannelComplaintOrderContext channelComplaintOrderContext = new ChannelComplaintOrderContext();
                channelComplaintOrderContext.setOrderComplaintChannelDO(channelDO);
                channelComplaintOrderContext.setProcessStatus(true);
                channelComplaintOrderContext.setComplaintNotifyUrl(channelDO.getComplaintNotifyUrl());
                CommonResult<String> commonResult = channelComplaintGateway.saveComplaintNotifyUrl(channelComplaintOrderContext);
                if(!channelComplaintOrderContext.isProcessStatus()){
                    commonResult.setMsg(channelComplaintOrderContext.getRemark());
                    return CommonResult.error(0,channelComplaintOrderContext.getRemark());
                }
                // 更新投诉回调地址成功
                String url = commonResult.getData();
                if(StrUtil.isEmpty(url)){
                    return CommonResult.error(0,"更新投诉回调通知失败，未获取到URL");
                }
                channelDO.setNotifyFlag(1);
                channelDO.setComplaintNotifyUrl(commonResult.getData());
            }

            // 判断是否更新风险回调地址
            if(StrUtil.isNotEmpty(channelDO.getRiskNotifyUrl())){
                // 合法校验
                if(!channelDO.getRiskNotifyUrl().startsWith("https")){
                    return CommonResult.error(CommonResultCode.PARAMETER_ERROR);
                }
                orderComplaintChannelDO = queryDetail(channelDO.getId());
                // 检查是否已经配置渠道
                if(StrUtil.isEmpty(orderComplaintChannelDO.getBaseConfig()) || StrUtil.isEmpty(orderComplaintChannelDO.getChannelCode())){
                    return CommonResult.error(MerchantResultCode.MERCHANT_COMPLAINT_CONFIG_NOT_EXIST);
                }
                // 校验是否更新过
                channelDO.setRiskFlag(orderComplaintChannelDO.getRiskFlag());

                ChannelRiskOrderContext channelRiskOrderContext = new ChannelRiskOrderContext();
                channelRiskOrderContext.setOrderComplaintChannelDO(channelDO);
                channelRiskOrderContext.setProcessStatus(true);
                channelRiskOrderContext.setRiskNotifyUrl(channelDO.getRiskNotifyUrl());
                CommonResult<String> commonResult = channelRiskGateway.saveRiskNotifyUrl(channelRiskOrderContext);
                if(!channelRiskOrderContext.isProcessStatus()){
                    commonResult.setMsg(channelRiskOrderContext.getRemark());
                    return CommonResult.error(0,channelRiskOrderContext.getRemark());
                }
                // 更新投诉回调地址成功
                String url = commonResult.getData();
                if(StrUtil.isEmpty(url)){
                    return CommonResult.error(0,"更新风险回调通知失败，未获取到URL");
                }
                channelDO.setRiskFlag(1);
                channelDO.setRiskNotifyUrl(commonResult.getData());
            }
            orderComplaintChannelMapper.updateById(channelDO);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("updateOrderComplaintChannel error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }

    }

    public CommonResult<Void> delBatch(ComplaintDeleteReq complaintDeleteReq){
        if(CollUtil.isNotEmpty(complaintDeleteReq.getId())){
            orderComplaintChannelMapper.deleteBatchIds(complaintDeleteReq.getId());
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<Void> delOrderComplaintChannel(Long id) {
        log.info("delete id:{}", id);
        try {
            if (id == null) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            OrderComplaintChannelDO orderComplaintChannelDO = queryDetail(id);
            if (orderComplaintChannelDO == null) {
                log.warn("delete 数据不存在 id:{}", id);
                return CommonResult.error(CommonResultCode.DATA_NOT_EXIST);
            }
            orderComplaintChannelMapper.deleteById(id);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("delOrderComplaintChannel error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    /**
     * 查询条件封装
     *
     * @param complaintOrderChannelQueryDto
     * @return
     */
    LambdaQueryWrapper<OrderComplaintChannelDO> buildWrapper(ComplaintOrderChannelQueryDto complaintOrderChannelQueryDto) {
        LambdaQueryWrapperX<OrderComplaintChannelDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.eqIfPresent(OrderComplaintChannelDO::getType,complaintOrderChannelQueryDto.getType());
        queryWrapper.eqIfPresent(OrderComplaintChannelDO::getStatus,complaintOrderChannelQueryDto.getStatus());
        queryWrapper.likeIfPresent(OrderComplaintChannelDO::getSubject, complaintOrderChannelQueryDto.getSubject());
        return queryWrapper;
    }
}
